import React, { useState, useEffect } from 'react';
import { TjFilter, TjModal, TjModalTitle } from '@/tjComponents';
import TjTable from '@/pages/ETrade/components/TjTable';
import { accountListColumns } from '../../helper';
import { Button, message, Modal, Pagination, Select } from 'antd';
import AddOrEditAccount from '../AddOrEditAccount';
import { addWf, deleteWf, getWfList, updateWf } from '../../service';
import { HttpCode } from '#/utils/contacts.js';
import { useSetState } from 'ahooks';
import './index.less';

const { confirm } = Modal;

const AccountList: React.FC<IAccountListProps> = (props) => {
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [req, setReq] = useSetState<any>({
    currentPage: 1,
    keyword: null,
    size: 20,
    regionIds: [],
  });
  const [initValue, setInitValue] = useState<any>();
  const [pagination, setPagination] = useSetState<any>({
    pageSize: 0,
    total: 0,
    currentPage: 1,
  });

  const add = () => {
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      content: <AddOrEditAccount regionList={props.regionList} />,
      maskClosable: false,
      destroyOnClose: true,
      onOk: (value) => {
        return new Promise((resolve, reject) => {
          addWf(value).then((res: any) => {
            if (res.statusCode === HttpCode.SUCCESS) {
              message.success('新增成功');
              resolve('');
              query();
            } else {
              message.error(res.message);
              reject();
            }
          });
        });
      },
    });
  };

  const edit = (row: any) => {
    TjModal.open({
      title: <TjModalTitle title="编辑" />,
      content: <AddOrEditAccount regionList={props.regionList} initValue={row} />,
      maskClosable: false,
      destroyOnClose: true,
      onOk: (value) => {
        return new Promise((resolve, reject) => {
          updateWf({ ...value, id: row.id }).then((res: any) => {
            if (res.statusCode === HttpCode.SUCCESS) {
              message.success('编辑成功');
              query();
              resolve('');
            } else {
              message.error(res.message);
              reject();
            }
          });
        });
      },
    });
  };

  const del = (id: string) => {
    confirm({
      title: '是否确认删除',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteWf(id).then((res: any) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            message.success('删除成功');
            query();
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };

  const query = () => {
    setLoading(true);
    getWfList(req)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          setDataSource(res.data);
          setPagination({
            pageSize: res.size,
            total: res.total,
            currentPage: res.current,
          });
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const changePagination = (page: number, pageSize?: number) => {
    setReq({
      currentPage: page,
      size: pageSize,
    });
  };

  const onSearch = (value: any) => {
    setReq({
      regionIds: [value.regionIds],
      keyword: value.keyword,
      currentPage: 1,
    });
  };

  useEffect(() => {
    if (req.regionIds && req.regionIds.length > 0) {
      query();
    }
  }, [req]);

  useEffect(() => {
    if (props.regionList && props.regionList.length > 0) {
      const firstRegionId = props.regionList[0] ? [props.regionList[0].value] : [];
      setReq({
        regionIds: firstRegionId,
      });
      setInitValue({
        regionIds: props.regionList[0].value,
      });
    }
  }, [props.regionList]);

  return (
    <div className="account-list">
      <div className="filter-box">
        <TjFilter
          defaultValues={initValue}
          onSearch={onSearch}
          items={[
            {
              name: 'regionIds',
              render: (
                <Select
                  options={props.regionList}
                  style={{ width: 150 }}
                  allowClear={false}
                  loading={loading}
                />
              ),
            },
            { name: 'keyword', placeholder: '请输入关键词' },
          ]}
          useResetBtn={false}
          loading={loading}
        />
        <Button type="link" onClick={add} loading={loading}>
          新增
        </Button>
      </div>
      <div className="table-box">
        <TjTable
          columns={accountListColumns({ edit, del })}
          dataSource={dataSource}
          isLoading={loading}
          primaryKey={'id'}
        />
      </div>

      <div className="pagination-box">
        <Pagination
          size="small"
          showSizeChanger
          showQuickJumper
          onChange={changePagination}
          total={pagination.total}
          showTotal={(total) => `共 ${total} 条`}
          pageSize={pagination.pageSize}
          current={pagination.currentPage}
        />
      </div>
    </div>
  );
};

interface IAccountListProps {
  regionList: any[];
}

export default AccountList;
